package 迭代器模式;

/**
 * 迭代器模式
 *  应用场景:  一般是研发底层的框架，比如提供某个数据给外部遍历，那么可以使用iterator模式自己封装迭代器，以后阶段如果有机会，我们也会去实践
 */
public class IteratorPattern {


    public static void main(String[] args) {
        Student dss = new Student("小明");
        Student dss1 = new Student("小红");

        Classroom classroom = new Classroom(2);
        classroom.addStudent(dss);
        classroom.addStudent(dss1);

        Iterator iterator = classroom.iterator();
        while (iterator.hasNext()) {
            Student next = (Student) iterator.next();
            System.out.println(next);
        }

    }

    public interface Iterator {
        /**
         * 是否有下一个元素
         * @return
         */
        public abstract boolean hasNext();

        /**
         * 获取下一个元素
         * @return
         */
        public abstract Object next();
    }


    /**
     * 一个迭代器
     */
    public interface Aggregate {
        /**
         * 获取迭代器
         * @return
         */
        public abstract Iterator iterator();
    }

    /**
     * 学生类
     */
    public static class Student {

        public Student(String name) {
            this.name = name;
        }

        public String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    /**
     * 教室
     */
    public static class Classroom implements Aggregate {

        private Student[] students;

        /**
         * 数组长度
         */
        private int last = 0;

        public Classroom(int size) {
            this.students = new Student[size];
        }

        public Student getStudent(int index) {
            return students[index];
        }

        public void addStudent(Student student) {
            this.students[last] = student;
            last++;
        }

        public int getLength() {
            return last;
        }

        @Override
        public Iterator iterator() {
            return new ClassRoomIterator(this);
        }
    }

    /**
     * 教室迭代器
     */
    public static class ClassRoomIterator implements Iterator {

        private Classroom classroom;
        private int index;

        public ClassRoomIterator(Classroom classroom) {
            this.classroom = classroom;
            this.index = 0;
         }

        @Override
        public boolean hasNext() {
            if (index < classroom.getLength()) {
                return true;
            }
            return false;
        }

        @Override
        public Object next() {
            Student student = classroom.getStudent(index);
            index++;
            return student;
        }
    }
}
